

import os

import mmcv
# using a pre-trained detector. 预训练配置
from mmcv import Config
from mmcv.runner import load_checkpoint

from mmdet.datasets import build_dataset
from mmdet.models import build_detector
from mmdet.apis import train_detector, inference_detector, show_result_pyplot

from mmdet.apis import init_detector, inference_detector, show_result_pyplot

# root_path=r"/project/train/src_repo/mmdetection/"
root_path=r"/home/deepin/Documents/ji_pingtai/mmdetection/"

config_file = root_path+'work_dir/cocoDataset_cfgformat.py'

checkpoint_file = root_path+'work_dir/latest.pth'

device = 'cuda:0'

# 初始化检测器--构建模型
model = init_detector(config_file, checkpoint_file, device=device)

# 查看 faster RCNN模型结构：
for name,module in model.named_children():
    print(name)
    [ print(F'    {n}') for n,_ in module.named_children() ]



# 推理 显示
# img = mmcv.imread(root_path+'data/coco/val2017/ZDSmask20220829_V8_train_office_2_003505.jpg')
img = mmcv.imread(root_path+'data/coco/val2017/2.jpg')

result = inference_detector(model, img) # -------如何 把 训练完成的，进行推理，这个不知道  如何加载呢

print(result)

# 先挑出来，conf_thres>= 0.3 的
# Load checkpoint
checkpoint = load_checkpoint(model, checkpoint_file, map_location=device)

import numpy as np
list_bboxs=[ ]
conf_thres = 0.3 # 置信度
for j in range(len(result)):

    for i, x in np.ndenumerate(result[j]):

        # print(i, x) # (1, 4) 0.25840828 ---每个 坐标的 值，及 坐标

        if i[1]==4 and x>=conf_thres :
            cl_numb=i[0] # 行号
            box=result[j][cl_numb]#找到 大于 置信度 那一行

            left = box[0]
            top = box[1]

            width = box[2]-box[0]
            height = box[3]-box[1]
            confidence = float(box[4])
            name = checkpoint['meta']['CLASSES'][j]

            list_bboxs.append((left,top,width,height,name,confidence))

print(list_bboxs)

show_result_pyplot(model, img, result,score_thr=0.3,out_file=root_path+'data/result.jpg') #显示

# 改写为ji自己的了--












